package visitor

import (
	"github.com/gin-gonic/gin"
	"database/sql"
	"chaoyer/ghost_assist/Nets"
	"chaoyer/ghost_assist/dao/visitordao"
	"chaoyer/ghost_assist/base/code"
)

// 访问数pv 增加
func AddPv(c *gin.Context) {

	postId, exits := c.GetPostForm("postId")
	if !exits || postId == "" {
		Nets.SendError(c, code.ARGS_NOT_ENOUGH)
		return
	}
	visitor, err := visitordao.FindByPostId(postId)
	if err != nil {
		if err != sql.ErrNoRows {
			Nets.SendError(c, code.SEVER_ERROR)
			return
		}
	}

	// 没有就增加一条
	if visitor.Id == 0 {
		visitor.PostId = postId
		_, err := visitordao.Insert(visitor)
		if err != nil {
			Nets.SendError(c, code.SEVER_ERROR)
			return
		}
	} else {
		// visitor++
		_, err := visitordao.UpdatePv(visitor)
		if err != nil {
			Nets.SendError(c, code.SEVER_ERROR)
			return
		}
	}
	data, _ := visitordao.FindByPostId(postId)
	Nets.SendData(c, data)
}

// 获取某一篇文章的pv
func GetPv(c *gin.Context) {

	postId, exist := c.GetQuery("postId")
	if !exist {
		Nets.SendError(c, code.ARGS_NOT_ENOUGH)
		return
	}
	visitor, err := visitordao.FindByPostId(postId)
	if Nets.CheckError(c, err, "文章不存在") {
		return
	}
	Nets.SendData(c, visitor)
}
